import 'package:family_expense/features/authentication/widgets/password_login.dart';
import 'package:family_expense/shared/services/data_initialization.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

/// IMPORTANT!!!
/// Even we do not use [setState] method here we still need the [StatefulWidget].
/// Because [Form] and [TextFormField] work with [StatefulWidget] only.
/// Otherwise once you tap on a [TextFormField] the keyboard closes after it opens right away.
class AccountUnregister extends StatefulWidget {
  const AccountUnregister({super.key});

  @override
  State<AccountUnregister> createState() => _AccountUnregisterState();
}

class _AccountUnregisterState extends State<AccountUnregister> {
  // IMPORTANT!!!
  // DO NOT CREATE THE KEY IN THE BUILD METHOD OR IN A [StatelessWidget]. OTHERWISE THE [TextFormField] WILL LOST FOCUS ONCE YOU TAP ON IT.
  // Creates a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool _inProgress = false;

  User? _user;
  String? _password;

  @override
  void initState() {
    super.initState();

    _getCurrentUser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: _buildForm());
  }

  /// Builds app bar.
  PreferredSizeWidget _buildAppBar() {
    return AppBar(title: const Text('注销账号'));
  }

  // Builds main input form.
  Widget _buildForm() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(30.0),
              child: Column(
                children: [
                  Icon(
                    MdiIcons.alertCircle,
                    size: 90.0,
                    color: const Color.fromRGBO(251, 112, 112, 1.0),
                  ),
                  const SizedBox(height: 10.0),
                  Text(
                    '此操作不可撤销',
                    style: Theme.of(context).textTheme.titleMedium,
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 20.0),
                  const Text(
                    '注销账号，将清除该账号组下所有数据，如银行卡、收支、类别等。再重复一次，此操作不可撤销，请慎重。',
                    style: TextStyle(color: Colors.black54, fontSize: 13.0),
                  ),
                  const SizedBox(height: 40.0),
                  const Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '身份验证',
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 15.0,
                      ),
                    ),
                  ),
                  const SizedBox(height: 20.0),
                  Container(
                    padding: const EdgeInsets.fromLTRB(15.0, 20.0, 15.0, 15.0),
                    color: Colors.white,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Row(
                          children: [
                            Text(
                              '当前账号',
                              style: Theme.of(context).textTheme.titleSmall!
                                  .copyWith(color: Colors.black54),
                            ),
                            Expanded(
                              child: Align(
                                alignment: Alignment.centerRight,
                                child: Text(
                                  _getCurrentUserFullName(),
                                  style: Theme.of(context).textTheme.titleSmall!
                                      .copyWith(color: Colors.black54),
                                ),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 15.0),
                        const Divider(),
                        TextFormField(
                          keyboardType: TextInputType.text,
                          obscureText: true,
                          decoration: InputDecoration(
                            hintText: '请输入密码',
                            hintStyle: Theme.of(context).textTheme.titleSmall!
                                .copyWith(color: Colors.black54),
                            // border: InputBorder.none,
                          ),
                          validator: (value) {
                            return FormTextFieldValidator(
                              '密码',
                              value,
                              minLength: User.passwordMinLength,
                              maxLength: User.passwordMaxLength,
                            ).validate();
                          },
                          onSaved: (value) => _password = value!,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(
                horizontal: 30.0,
                vertical: 30.0,
              ),
              child: PressStatusButton(
                onPressed: _unregister,
                inProgress: _inProgress,
                disabledChild: const Text('正在注销'),
                child: const Text('确认注销'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Gets current authenticated user.
  Future<void> _getCurrentUser() async {
    final user = await AuthStateService.instance.currentUser;

    if (mounted) {
      setState(() => _user = user!);
    }
  }

  String _getCurrentUserFullName() {
    if (_user == null) {
      return '';
    }

    final result = _user!.username == _user!.fullName
        ? _user!.fullName
        : '${_user!.fullName} (${_user!.username!.formatMobilePhoneNumber()})';

    return result!;
  }

  /// Unregisters account group by current admin user.
  /// Unregisters user data by current user.
  Future<void> _unregister() async {
    // Validate returns true if the form is valid, or false otherwise.
    if (!_formKey.currentState!.validate()) {
      showToast('请正确填写各项信息');
      return;
    }

    showConfirmDialog(
      context,
      '此操作不可撤销，再次确认，是否注销？',
      onConfirm: () async {
        if (mounted) {
          setState(() => _inProgress = true);
        }

        // Saves current form.
        _formKey.currentState!.save();

        // Unregisters current account group.
        final error = await AuthService().unregister(_password!);

        if (error.isNullOrEmpty) {
          // When it's done logs out from server. It would clears user token.
          showToast('已完成注销，自动返回登录界面。');

          final authStateService = AuthStateService.instance;

          // Removes user from collection. This is for quick login widget.
          authStateService.removeFromUserInfoCollection(_user!);

          // Saves current username for next logic form auto fill input.
          authStateService.saveCurrentUsername();

          // Removes local user info.
          authStateService.removeUserInfo();

          // Removes local token info.
          TokenService.removeToken();

          // Clears cache data.
          DataInitialization().clear();

          // DO NOT use BuildContext across asynchronous gaps.
          // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
          if (mounted) {
            // Once it's done we need to redirect to login and clear all previous routes.
            // It makes user stay on login page and no turning back.
            NavigatorHelper.pushAndRemoveUntil(
              context,
              const PasswordLogin(),
              (route) => false,
            );
          }
        } else {
          if (error == 'ERROR_USER_ACCOUNT_BAD_CREDENTIAL') {
            showToast('输入的密码有误，请重新尝试。');
          } else {
            showToast('服务处理发生异常，请重新尝试。');
          }
        }

        if (mounted) {
          setState(() => _inProgress = false);
        }
      },
    );
  }
}
